iT邦幫忙

2024 iThome 鐵人賽

DAY 5
0

現在我們有基本的模板的雛型了,
這樣可以思考一下設定檔大概是甚麼樣子,
原本預計應該是後端api會給一個json陣列,
畫面上要幾個欄位 陣列裡面就有幾組設定,
目前控制版面的參數有四個,
這樣預計中的json大概是這個樣子

fieldSettings:[
    {
            name: 'text1',
            cname: '文字欄位1',
            inputType: 'text',
            placeholder: '請輸入文字',
            required: true,
    },
    {
            name: 'number1',
            cname: '數字欄位',
            inputType: 'number',
            placeholder: '請輸入數字',
            required: true,
    },
]

把這個樣式加到main以後,
main.component.html就可以調整成ngFor的迴圈去處理

<div *ngFor="let fieldSetting of fieldSettings">
  <app-field-template
    title="{{ fieldSetting.cname }}"
    [required]="fieldSetting.required"
    type="{{ fieldSetting.inputType }}"
    placeholder="{{ fieldSetting.placeholder }}"
  ></app-field-template>
</div>

針對上面fieldSetting,
我們產生一個對應的interface放在element下面,
這邊增加defaultValue,
用來處理欄位有時候可能需要預設值,
由於可能用不到所以允許undefined

// 在/shared/component/form/element
// 新增檔案field-setting.model.ts
export interface FieldSetting
{
    name: string;
    cname: string;
    inputType: string;
    placeholder: string;
    required: boolean;
    defaultValue?: string | undefined;
}

由於變數之後有可能會越來越多,
這邊決定我們傳遞fieldSetting就好,
於是由外到內的程式會變成這樣

// main.componet.html

<div *ngFor="let fieldSetting of fieldSettings">
  <app-field-template [fieldSetting]="fieldSetting"> </app-field-template>
</div>


// field-template.component.ts

    @Input() fieldSetting!: FieldSetting;

    // @Input() type: string = 'text';
    // @Input() title: string = '標題';
    // @Input() required: boolean = false;
    // @Input() placeholder: string | undefined;
    
    
// field-template.component.html

<div style="padding-bottom: 8px">
  <span>
    {{ fieldSetting.cname }}
    <span *ngIf="fieldSetting.required" style="color: red">*</span>:
  </span>
  <app-field [fieldSetting]="fieldSetting"></app-field>
</div>


// field.component.ts

    @Input() fieldSetting!: FieldSetting;

    // @Input() type: string = 'text';
    // @Input() placeholder: string | undefined;
    

// field.component.html

<div [ngSwitch]="fieldSetting.inputType">
  <div *ngSwitchCase="'text'">
    <app-base-text [placeholder]="fieldSetting.placeholder"></app-base-text>
  </div>
  <div *ngSwitchCase="'tel'">
    <app-base-tel [placeholder]="fieldSetting.placeholder"></app-base-tel>
  </div>
  <div *ngSwitchCase="'number'">
    <app-base-number [placeholder]="fieldSetting.placeholder"></app-base-number>
  </div>
  <div *ngSwitchCase="'password'">
    <app-base-password
      [placeholder]="fieldSetting.placeholder"
    ></app-base-password>
  </div>
</div>


由於現在都是由fieldSetting控制,
所以裡面原本的input都可以拿掉換成fieldSetting,
雖然這樣元件的彈性會變低,
不過為了開發的方便,目前先調整成這樣,
如果之後有其他需要再來重購

決定好設定檔以後也許隱約會發現一個問題,
欄位是產出來了,但是這樣要怎麼處理欄位的資料呢,
實際寫起來篇幅有點多,於是就切到明天再說囉~
我們明天見!

今日程式:day05


上一篇
第4天:調整模版
下一篇
第6天 資料綁定
系列文
簡單的事 最困難-Angular動態Form元件14
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言